package com.jrzh.mvc.service.sys.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jrzh.common.exception.ProjectException;
import com.jrzh.common.tools.CollectionTools;
import com.jrzh.common.utils.PasswordUtils;
import com.jrzh.config.ProjectConfigration;
import com.jrzh.framework.I18nHelper;
import com.jrzh.framework.bean.SessionUser;
import com.jrzh.framework.contants.GeneralConstant;
import com.jrzh.mvc.constants.SysFileConstants;
import com.jrzh.mvc.constants.UserSettingConstants;
import com.jrzh.mvc.model.sys.ResourcesModel;
import com.jrzh.mvc.model.sys.RoleModel;
import com.jrzh.mvc.model.sys.UserModel;
import com.jrzh.mvc.search.sys.FileSearch;
import com.jrzh.mvc.search.sys.UserSearch;
import com.jrzh.mvc.search.sys.UserSettingSearch;
import com.jrzh.mvc.service.sys.FileServiceI;
import com.jrzh.mvc.service.sys.LoginServiceI;
import com.jrzh.mvc.service.sys.ResourcesServiceI;
import com.jrzh.mvc.service.sys.RoleServiceI;
import com.jrzh.mvc.service.sys.UserServiceI;
import com.jrzh.mvc.service.sys.UserSettingServiceI;
import com.jrzh.mvc.view.sys.FileView;
import com.jrzh.mvc.view.sys.UserSettingView;

@Service("loginService")
public class LoginServiceImpl  implements LoginServiceI{
	public Log log = LogFactory.getLog(getClass());
	@Resource(name="userService")
	private UserServiceI userService;
	
	@Resource(name = "fileService")
	private FileServiceI fileService;
	
	@Resource(name = "userSettingService")
	private UserSettingServiceI userSettingService;
	
	@Resource(name = "projectConfigration")
	private ProjectConfigration projectConfigration;
	
	@Autowired
	private RoleServiceI roleService;
	
	@Autowired
	private ResourcesServiceI resourcesService;
	
	public SessionUser login(String loginName, String loginPass, String host)  throws ProjectException{
		SessionUser sessionUser = new SessionUser();
		Map<String, Object> attrs = sessionUser.getAttrs();
		if(null == attrs) attrs = new HashMap<String, Object>();
		UserSearch userSearch = new UserSearch();
		userSearch.setEqualCode(loginName);
		List<UserModel> userList  = userService.list(userSearch);
		if (CollectionTools.isBlank(userList)) {
			throw new ProjectException("用户不存在");
		}
		UserModel userModel = userList.get(0);
		String realPass = PasswordUtils.encryptPassword(loginPass, userModel.getSalt());
		if (!StringUtils.equals(userModel.getPassword(),realPass)) {
			throw new ProjectException("密码错误");
		}
		if (userModel.getIsDisable()) {
			throw new ProjectException("用户被禁止登录");
		}
		
		FileSearch fileSearch = new FileSearch();
		fileSearch.setEqualFormId(userModel.getId());
		fileSearch.setEqKey(SysFileConstants.FILE_KEY.ADMIN_PHOTO);
		fileSearch.setEqualModel(SysFileConstants.FILE_MODEL.SYS_USER);
		try {
			FileView fileView = fileService.findViewBySearch(fileSearch);
			if(null != fileView) {
				sessionUser.setPhoto(fileView.getUrl());
			}
		} catch (Exception e) {
			log.error("获取用户头像失败");
		}
		String lang = projectConfigration.defaultI18n;
		try {
			UserSettingSearch settingSearch = new UserSettingSearch();
			settingSearch.setEqualUserId(userModel.getId());
			List<UserSettingView> settingList = userSettingService.viewList(settingSearch);
			attrs.put("setting", settingList);
			UserSettingView langSetting = CollectionTools.searchObject(settingList, "key", UserSettingConstants.ADMIN_LANG);
			if(null != langSetting) {
				lang = langSetting.getValue();
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取用户语言失败");
		}
		attrs.put("lang", lang);
		try {
			//权限存入缓存
			Set<String> roles = new HashSet<String>();
			Set<String> roleNames = new HashSet<String>();
			Set<String> resources = new HashSet<String>();
			//如果是超级管理员就赋予所有权限
			if(StringUtils.equals(userModel.getCode(), GeneralConstant.USER_CODE_CONSTANT.SUPER_ADMIN_CODE)){
				List<RoleModel> roleList = roleService.selectByField("isDisable", false);
				//List<ResourcesModel> resourceList = resourcesService.selectByField("isDisable", false);
				List<ResourcesModel> resourceList = resourcesService.findAll();
				roleNames.add("系統管理員");
				if(null != roleList && roleList.size() > 0){
					for(RoleModel role : roleList){
						roles.add(role.getCode());
					}
				}
				if(null != resourceList && resourceList.size() > 0){
					for(ResourcesModel resource : resourceList){
						resources.add(resource.getCode());
					}
				}
			}else{
				List<RoleModel> roleList = userModel.getRoles();
				if(null != roleList && roleList.size() > 0){
					for(RoleModel role : roleList){
						roles.add(role.getCode());
						roleNames.add(role.getName());
						List<ResourcesModel> resourcesList = role.getResources();
						if(null != resourcesList && resourcesList.size() > 0){
							for(ResourcesModel resource : resourcesList){
								resources.add(resource.getCode());
							}
						}
					}
				}
			}
			
			attrs.put("roles", roles);
			attrs.put("resources", resources);
			sessionUser.setRoleName(StringUtils.join(roleNames,","));
		} catch (Exception e) {
			try {
				throw new ProjectException(I18nHelper.getI18nByKey("message.operation_success", sessionUser));
			} catch (ProjectException e1) {
				e1.printStackTrace();
			}
		}
		sessionUser.setId(userModel.getId());
		sessionUser.setCode(userModel.getCode());
		sessionUser.setName(userModel.getName());
		sessionUser.setAttrs(attrs);
		return sessionUser;
	}
}
